package com.landeb.shop.huo.act;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.landeb.shop.R;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.aliPay.AliPay;
import com.landeb.shop.huo.bean.BeanActOrderDetail;
import com.landeb.shop.huo.bean.BeanActPayDetail;
import com.landeb.shop.huo.bean.BeanAliPayRequst;
import com.landeb.shop.huo.bean.BeanStatusInfo;
import com.landeb.shop.huo.bean.BeanWXPayRequest;
import com.landeb.shop.huo.httpRequest.ActPayRequest;
import com.landeb.shop.huo.httpRequest.UserConfirmationRequest;
import com.landeb.shop.wxapi.WXPayEntryActivity;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class PayActivity extends BaseActivity implements View.OnClickListener {

    private String mOrderId;

    private SwipeRefreshLayout mSRL;
    private TextView tvPrice, tvBalance, tvLiuShuiHao, tvZhiFuXiangQing;
    private EditText etPassword;
    private Button btnPay;
    private LinearLayout btnBack, llAliPay, llWxPay, llPayContainer;

    private OkHttpClient mClient;
    private Retrofit mRetrofit;
    private String mUrl;
    private ActPayRequest mRequest;

    /**
     * 设置商户PID
     */
    public static final String PARTNER = "";

    /**
     * 商户收款账号
     */
    public static final String SELLER = "";

    /**
     * 商户私钥，pkcs8格式
     */
    public static final String RSA_PRIVATE = "";

    public static void toAct(Context context) {
        Intent intent = new Intent(context, PayActivity.class);
        context.startActivity(intent);
    }

    public static void toAct(Context context, String orderId) {
        Intent intent = new Intent(context, PayActivity.class);
        intent.putExtra("orderId", orderId);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);

        Intent intent = getIntent();
        mOrderId = intent.getStringExtra("orderId");


        mClient = MyApplication.getClient();
        mUrl = MyApplication.BASE_URL;
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(mClient)
                .build();
        mRequest = mRetrofit.create(ActPayRequest.class);

        initView();
        initData();
        initEvent();

        refresh();

    }

    private void refresh() {

        mSRL.setRefreshing(true);

        mRequest.getPayDetail(mOrderId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BeanActPayDetail>() {
                    @Override
                    public void onCompleted() {
                        mSRL.setRefreshing(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        mSRL.setRefreshing(false);
                    }

                    @Override
                    public void onNext(BeanActPayDetail beanActPayDetail) {
                        if (beanActPayDetail.getStatus() == 1) {
                            tvPrice.setText("¥" + beanActPayDetail.getData().getMoney());
                            tvBalance.setText("¥" + beanActPayDetail.getData().getUser_money());
                            tvLiuShuiHao.setText(beanActPayDetail.getData().getId());
                            tvZhiFuXiangQing.setText(beanActPayDetail.getData().getContent());

                            if (beanActPayDetail.getData().getAllow_balance().equals("1")) {
                                llPayContainer.setVisibility(View.VISIBLE);
                            } else {
                                llPayContainer.setVisibility(View.GONE);
                            }

                        } else {
                            Toast.makeText(PayActivity.this, beanActPayDetail.getInfo(), Toast.LENGTH_SHORT).show();
                        }

                    }
                });

//        mRequest.getMoney(mOrderId)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Subscriber<BeanActOrderDetail>() {
//                    @Override
//                    public void onCompleted() {
//                        mSRL.setRefreshing(false);
//
//                        Log.e("getMoney", "onCompleted: ");
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        mSRL.setRefreshing(false);
//
//                        Log.e("getMoney", "onError: " + e.toString());
//
//                    }
//
//                    @Override
//                    public void onNext(BeanActOrderDetail beanActOrderDetail) {
//
//                        if (beanActOrderDetail.getStatus() == 1) {
//                            tvPrice.setText("¥" + beanActOrderDetail.getData().getMoney());
//                            tvBalance.setText("¥" + beanActOrderDetail.getData().getUser_money());
//                        } else {
//                            Toast.makeText(PayActivity.this, beanActOrderDetail.getInfo(), Toast.LENGTH_SHORT).show();
//                        }
//
//                    }
//                });

    }

    private void initEvent() {

        btnBack.setOnClickListener(this);
        btnPay.setOnClickListener(this);
        llWxPay.setOnClickListener(this);
        llAliPay.setOnClickListener(this);

    }

    private void initData() {

    }

    private void initView() {

        mSRL = (SwipeRefreshLayout) findViewById(R.id.act_pay_srl);
        mSRL.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
        mSRL.setEnabled(false);

        btnBack = (LinearLayout) findViewById(R.id.act_pay_btn_back);
        tvPrice = (TextView) findViewById(R.id.act_pay_tv_price);
        tvBalance = (TextView) findViewById(R.id.act_pay_tv_accountBalance);
        btnPay = (Button) findViewById(R.id.act_pay_btn_pay);
        llAliPay = (LinearLayout) findViewById(R.id.act_pay_ll_aliPay);
        llWxPay = (LinearLayout) findViewById(R.id.act_pay_ll_wxPay);
        etPassword = (EditText) findViewById(R.id.act_pay_et_pay_code);

        tvLiuShuiHao = (TextView) findViewById(R.id.act_pay_tv_liushuihao);
        tvZhiFuXiangQing = (TextView) findViewById(R.id.act_pay_tv_zhifuxiangqing);
        llPayContainer = (LinearLayout) findViewById(R.id.act_pay_ll_pay_container);
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.act_pay_btn_back:
                // TODO: 2016/11/27 返回键
                onBackPressed();
                break;

            case R.id.act_pay_btn_pay:
                // TODO: 2016/11/27 余额支付

                if (etPassword.getText().toString().isEmpty()) {
                    Toast.makeText(PayActivity.this, "请输入支付密码", Toast.LENGTH_SHORT).show();
                    return;
                }

                final ProgressDialog dialog = new ProgressDialog(PayActivity.this);
                dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                dialog.setCancelable(false);
                dialog.setMessage("请稍后");
                dialog.show();

                mRequest.balancePay(mOrderId, etPassword.getText().toString())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<BeanStatusInfo>() {
                            @Override
                            public void onCompleted() {
                                Log.e("balancePay", "onCompleted: ");
                                dialog.dismiss();
                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.e("balancePay", "onCompleted: ");
                                dialog.dismiss();
                            }

                            @Override
                            public void onNext(BeanStatusInfo beanStatusInfo) {

                                if (beanStatusInfo.getStatus() == 1) {

                                    Toast.makeText(PayActivity.this, beanStatusInfo.getInfo(), Toast.LENGTH_SHORT).show();

                                } else {

                                    AlertDialog.Builder builder = new AlertDialog.Builder(PayActivity.this);
                                    builder.setTitle("系统提示")
                                            .setMessage(beanStatusInfo.getInfo())
                                            .setCancelable(false)
                                            .setPositiveButton("确定", null)
                                            .show();

                                }

                            }
                        });

                break;

            case R.id.act_pay_ll_aliPay:
                // TODO: 2016/11/27 支付宝支付


                final ProgressDialog progressDialog = new ProgressDialog(PayActivity.this);
                progressDialog.setMessage("正在加载，请稍后");
                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                progressDialog.setCancelable(false);
                progressDialog.show();

                mRequest.getAliInfo(mOrderId)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<BeanAliPayRequst>() {
                            @Override
                            public void onCompleted() {
                                Log.e("getAliInfo", "onCompleted: ");
                                progressDialog.dismiss();
                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.e("getAliInfo", "onError: " + e.toString());
                                progressDialog.dismiss();

                            }

                            @Override
                            public void onNext(BeanAliPayRequst beanAliPayRequst) {

                                if (beanAliPayRequst.getStatus() == 1) {

                                    String oderInfo = beanAliPayRequst.getData().getConfig();

                                    Log.e("orderInfo: ", "+start+" + oderInfo);

                                    AliPay.Builder builder = new AliPay.Builder(PayActivity.this);
                                    builder.setOrderIfo(oderInfo).setPayCallBackListener(new AliPay.Builder.PayCallBackListener() {
                                        @Override
                                        public void onPayCallBack(int status, String resultStatus, String progress) {
                                            // TODO: 2016/11/30 支付回调 status==9000时 为支付成功
                                            if (status == 9000) {

                                                OrderDetailActivity.toAct(PayActivity.this, mOrderId);

                                            } else {

                                                AlertDialog.Builder builder = new AlertDialog.Builder(PayActivity.this);
                                                builder.setTitle("系统提示")
                                                        .setMessage("支付失败，请重试")
                                                        .setCancelable(false)
                                                        .setPositiveButton("确定", null)
                                                        .show();

                                            }
                                        }
                                    });
                                    builder.myPay();

                                } else {

                                    Toast.makeText(PayActivity.this, beanAliPayRequst.getInfo(), Toast.LENGTH_SHORT).show();
                                }

                            }
                        });


                break;

            case R.id.act_pay_ll_wxPay:
                // TODO: 2016/11/27 微信支付
//                Log.e("act_pay_ll_wxPay", "onClick: ");
//                WXPayEntryActivity.WXPay(PayActivity.this);

                final ProgressDialog progressDialog4wx = new ProgressDialog(PayActivity.this);
                progressDialog4wx.setMessage("正在加载，请稍后");
                progressDialog4wx.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                progressDialog4wx.setCancelable(false);
                progressDialog4wx.show();

                mRequest.getWXInfo(mOrderId)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<BeanWXPayRequest>() {
                            @Override
                            public void onCompleted() {
                                progressDialog4wx.dismiss();
                            }

                            @Override
                            public void onError(Throwable e) {
                                progressDialog4wx.dismiss();
                            }

                            @Override
                            public void onNext(BeanWXPayRequest beanWXPayRequest) {

                                if (beanWXPayRequest.getStatus()==1) {

                                    WXPayEntryActivity.WXPay(PayActivity.this, beanWXPayRequest.getData());
                                }else {

                                    Toast.makeText(PayActivity.this,beanWXPayRequest.getInfo(),Toast.LENGTH_SHORT).show();

                                }



                            }
                        });

                break;

        }

    }
}
